<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import $api from "@/api/index.js"
	import $store from "@/store/index.js"
	export default {
		data() {
			return {
				isLoad: false,
				timer: null,
				travelTimer: null
			}
		},
		async mounted() {
			// #ifdef H5
			if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
				window.entryUrl = window.location.href.split('#')[0]
			}
			if (window.location.href.indexOf('?#') < 0) {
				window.location.href = window.location.href.replace("#", "?#")
			}
			// #endif
			console.log('App mounted')
		},
		async onLaunch() {
			let configInfo = uni.getStorageSync('configInfo') || ''
			if (configInfo) {
				$store.commit('updateConfigItem', {
					key: 'configInfo',
					val: configInfo
				})
			}
			let isGzhLogin = uni.getStorageSync('isGzhLogin') || false
			$store.commit('updateUserItem', {
				key: 'isGzhLogin',
				val: isGzhLogin
			})
			$store.commit('updateUserItem', {
				key: 'changeAddr',
				val: false
			})
			let arr = ['userInfo', 'autograph', 'location', 'locaRefuse', 'appLogin', 'loginType',
				'loginPage'
			]
			arr.map(key => {
				let val = uni.getStorageSync(key) || ''
				if (key == 'locaRefuse') {
					val = val || false
				}
				// #ifdef H5
				// val = isGzhLogin ? val : ''
				// #endif
				$store.commit('updateUserItem', {
					key,
					val
				})
				// #ifdef APP-PLUS
				if (key == 'userInfo') {
					$store.commit('updateUserItem', {
						key: 'isShowLogin',
						val: val && val.id ? false : true
					})
				}
				// #endif
			})
			let {
				commonOptions
			} = this
			let {
				coach_id = 0
			} = commonOptions
			if (coach_id) {
				commonOptions.coach_id = 0
				$store.commit('updateUserItem', {
					key: 'commonOptions',
					val: commonOptions
				})
			}
			this.initIndex()
			console.log('App onLaunch')
		},
		async onShow() {
			if (this.timer) clearInterval(this.timer)
			await this.getUserCoachStatus()
			$store.commit('updateUserItem', {
				key: 'locationChange',
				val: this.userCoachStatus.coach_position == 1
			})
			let {
				coach_travel_order_id
			} = this
			this.updateOrderItem({
				key: 'coach_travel_order_id',
				val: coach_travel_order_id
			})
			uni.onNetworkStatusChange((res) => {
				let {
					isConnected
				} = res
				if (isConnected) return
				let methodArr = ['updateServiceItem', 'updateTechnicianItem', 'updateMapItem',
					'updateDynamicItem', 'updateShopstoreItem', 'updateOrderItem'
				]
				methodArr.map(item => {
					$store.commit(item, {
						key: 'pageActive',
						val: false
					})
				})
			})
		},
		async onHide() {
			console.log('App Hide')
			let {
				status = 0,
					coach_position = 0
			} = this.userCoachStatus
			if (coach_position && status == 2) {
				$store.commit('updateUserItem', {
					key: 'locationChange',
					val: false
				})
				// #ifdef H5
				if (this.$jweixin.isWechat()) {
					await this.$jweixin.wxReady2();
					this.toHidePage()
					this.timer = setInterval(() => {
						this.toHidePage()
					}, 60000)
				}
				// #endif
			}
			if (this.coach_travel_order_id) {
				this.toAddCoachTravel()
			}
		},
		onUnload() {
			uni.offLocationChange((res) => {
				console.log("====offLocationChange onUnload", res)
			})
		},
		watch: {
			'configInfo.attendant_name'(newVal, oldVal) {
				if (newVal) {
					this.mergeLocaleMessage()
				}
			},
			locationChange(newVal, oldVal) {
				if (newVal) {
					uni.startLocationUpdate({
						complete: msg => console.log(`startLocationUpdate API complete`, msg)
					})
				} else {
					uni.stopLocationUpdate({
						complete: msg => console.log(`stopLocationUpdate API complete`, msg)
					})
				}
			},
			coach_travel_order_id(newVal, oldVal) {
				if (newVal) {
					this.toAddCoachTravel()
				}
			},
			coach_travel_arrive_id(newVal, oldVal) {
				if (this.travelTimer) clearInterval(this.travelTimer)
				if (newVal) {
					this.updateOrderItem({
						key: 'coach_travel_order_id',
						val: 0
					})
					this.toConfirmAddCoachTravel(newVal)
				}
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			old_attendant_name: state => state.config.old_attendant_name,
			commonOptions: state => state.user.commonOptions,
			locationChange: state => state.user.locationChange,
			locationChangeUnix: state => state.user.locationChangeUnix,
			userInfo: state => state.user.userInfo,
			userCoachStatus: state => state.user.userCoachStatus,
			coach_travel_order_id: state => state.order.coach_travel_order_id
		}),
		methods: {
			...mapActions(['getConfigInfo', 'getUserInfo', 'getUserCoachStatus']),
			...mapMutations(['updateOrderItem']),
			async initIndex() {
				let that = this
				await this.getUserCoachStatus()
				uni.onLocationChange((res) => {
					console.log("====onLocationChange", res)
					let {
						latitude: lat,
						longitude: lng
					} = res
					that.toChangeLocation({
						lat,
						lng
					})
				})
				$store.commit('updateUserItem', {
					key: 'locationChange',
					val: this.userCoachStatus.coach_position == 1
				})
				await that.getConfigInfo()
				this.isLoad = true
			},
			async mergeLocaleMessage() {
				let zh = JSON.parse(JSON.stringify(this.$i18n.messages.zh))
				let {
					attendant_name: name,
				} = this.configInfo
				let oldName = this.old_attendant_name
				let reg = new RegExp(oldName, 'g')
				for (let i in zh.action) {
					if (zh.action[i].includes(oldName)) {
						zh.action[i] = zh.action[i].replace(reg, name)
					}
				}
				this.$i18n.mergeLocaleMessage('zh', zh)
				$store.commit('updateConfigItem', {
					key: 'old_attendant_name',
					val: name
				})
				// console.log(this.$t('action.attendantName'), this.$i18n.messages.zh, "=====");
			},
			async toHidePage() {
				// #ifdef H5
				let {
					latitude: lat,
					longitude: lng
				} = await this.$jweixin.getWxLocation()
				// #endif
				// #ifndef H5
				let {
					lat,
					lng
				} = await this.$util.getBmapLocation()
				// #endif
				if (lat && lng) {
					let val = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
					$store.commit('updateUserItem', {
						key: 'locationChangeUnix',
						val
					})
					this.toChangeLocation({
						lat,
						lng
					})
				}
			},
			async toChangeLocation(param) {
				let {
					lat,
					lng
				} = param
				let {
					status: coach_status = 0,
					coach_position = 0
				} = this.userCoachStatus
				let {
					locationChangeUnix
				} = this
				let curUnix = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
				let second = 3
				// #ifdef APP-PLUS
				second = 1
				// #endif
				// console.log(curUnix, locationChangeUnix, curUnix - locationChangeUnix, "=====curUnix - locationChangeUnix")
				let isMin = (curUnix - locationChangeUnix <= second) || (curUnix - locationChangeUnix >= 60)
				if (!coach_position || coach_status != 2 || !isMin) return

				let val = this.$util.DateToUnix(this.$util.formatTime(new Date(), 'YY-M-D h:m:s'))
				$store.commit('updateUserItem', {
					key: 'locationChangeUnix',
					val
				})

				let key = `${lat},${lng}`
				try {
					let data = await this.$api.base.getMapInfo({
						location: key
					})
					let {
						status,
						result
					} = JSON.parse(data)
					if (status == 0 || status == 1) {
						let {
							address = '暂未获取到位置信息',
								formatted_addresses = {}
						} = result
						if (status == 0) {
							let {
								standard_address
							} = formatted_addresses
							address = standard_address
						}
						console.log("toChangeLocation==>", `${lat}-${lng}-${address}`)
						await this.$api.technician.coachUpdate({
							lat,
							lng,
							address
						})
						await this.getUserCoachStatus()
					}
				} catch (e) {
					console.log('=====getMapInfo catch')
					uni.stopLocationUpdate({
						complete: msg => console.log(`stopLocationUpdate API complete`, msg)
					})
				}
			},
			async toAddCoachTravel() {
				let {
					coach_travel_order_id
				} = this
				let {
					coachtravel
				} = this.configInfo.plugAuth
				let {
					id: uid
				} = this.userInfo
				if (this.travelTimer) clearInterval(this.travelTimer)
				if (!coachtravel || !coach_travel_order_id || !uid) return
				this.toConfirmAddCoachTravel(coach_travel_order_id)
				this.travelTimer = setInterval(() => {
					this.toConfirmAddCoachTravel(coach_travel_order_id)
				}, 5000)
			},
			async toConfirmAddCoachTravel(order_id) {
				let location = {}
				// #ifdef H5
				if (this.$jweixin.isWechat()) {
					await this.$jweixin.wxReady2();
					let {
						latitude: lat = 0,
						longitude: lng = 0
					} = await this.$jweixin.getWxLocation()
					location = {
						lat,
						lng,
						address: ''
					}
				}
				// #endif
				// #ifndef H5
				location = await this.$util.getBmapLocation()
				// #endif
				let {
					lat,
					lng,
					address
				} = location
				if (lat && lng) {
					await this.$api.technician.coachTrajectoryAdd({
						order_id,
						text: {
							lat,
							lng,
							address
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	@import "/styles/index.wxss";

	/* #ifdef H5 */
	uni-page-head {
		display: none;
	}

	/* #endif */
	.map-box .csssprite {
		border: 2px solid #fff !important;
		box-sizing: border-box;
		box-shadow: 0 2px 6px 0 rgba(0, 0, 0, 0.1);
		border-radius: 50% !important;
	}

	.map-box a div .csssprite {
		display: none;
	}

	page {
		font-size: 28rpx;
		color: #222;
		line-height: 1.5;
		background: #F6F6F6;
		font-family: -apple-system-font, Helvetica Neue, Helvetica, sans-serif;
	}

	input {
		// font-family: PingFangSC-Medium, PingFang SC, -apple-system-font, Helvetica Neue, Helvetica, sans-serif;
	}

	input::-webkit-input-placeholder {
		/* WebKit browsers */
		color: #A9A9A9;
	}

	input:-moz-placeholder {
		/* Mozilla Firefox 4 to 18 */
		color: #A9A9A9;
	}

	input::-moz-placeholder {
		/* Mozilla Firefox 19+ */
		color: #A9A9A9;
	}

	input:-ms-input-placeholder {
		/* Internet Explorer 10+ */
		color: #A9A9A9;
	}

	view {
		box-sizing: border-box;
	}

	image {
		display: block;
	}

	.h5-image {
		background-position: center center;
		background-size: cover;
		background-repeat: no-repeat;
	}

	/*隐藏滚动条*/
	::-webkit-scrollbar {
		width: 0;
		height: 0;
		color: transparent;
	}

	/* #ifdef MP-BAIDU */
	.swan-button.swan-button-radius-ios {
		border-radius: 0;
	}

	/* #endif */
</style>